<template>
  <div>
    <!-- 面包屑导航 -->
    <tab-control :title="['首页','商品管理','参数列表']"></tab-control>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert
        title="注意:只允许为第三级分类设置相关参数!"
        type="warning"
        :closable="false"
        show-icon
      ></el-alert>

      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs
        v-model="activeName"
        @tab-click="handleClick"
        style="width: 99.9% !important"
      >
        <!-- 添加动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            size="mini"
            @click="addDialog = true"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyData" border stripe v-if="activeName === 'many'">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                  <!-- 添加按钮 -->
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            size="mini"
            type="primary"
            :disabled="isBtnDisabled"
            @click="addDialog = true"
            >添加属性</el-button
          >
          <!-- 静态属性表格 -->
          <el-table :data="onlyData" border stripe v-if="activeName === 'only'">
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  closable
                  @close="handleClose(i, scope.row)"
                  >{{ item }}</el-tag
                >
                <!-- 输入文本框 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                  <!-- 添加按钮 -->
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row)"
                  >修改</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialog"
      width="30%"
      @close="addDialogClose"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>
        <el-button type="primary" @click="addParameter">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialog"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        label-width="100px"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialog = false">取 消</el-button>
        <el-button type="primary" @click="editParameter">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TabControl from '@/components/tabcontrol/TabControl.vue'
import {
  getAllCateList,
  parameterList,
  addParameter,
  editParameter,
  removeParams,
  submitEditParameters,
} from "@/api/utils";
export default {
  name: "params",
  components:{
    TabControl
  },
  data() {
    return {
      cateList: [],
      cateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
      selectCateKeys: [],
      activeName: "many",
      manyData: [],
      onlyData: [],
      addDialog: false,
      addForm: {
        attr_name: "",
      },
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      editDialog: false,
      editForm: {
        attr_name: "",
        attr_id: "",
        attr_sel: "",
        attr_vals: "",
      },
      editFormRules: {
        attr_name: [
          { required: true, message: "请输入参数名称", trigger: "blur" },
        ],
      },
      inputVisible: false,
      inputValue: "",
    };
  },
  created() {
    this.getAllCateList();
  },
  methods: {
    //获取所有商品分类列表
    getAllCateList() {
      getAllCateList().then((res) => {
        // console.log(res);
        if (res.meta.status != 200)
          return this.$message.error("获取商品分类失败!");
        this.cateList = res.data;
      });
    },
    // 级联选择框选择项触发函数
    handleChange() {
      if (this.selectCateKeys.length != 3) {
        this.selectCateKeys = [];
        this.manyData = [];
        this.onlyData = [];
        return;
      }
      this.parameterList();
    },
    //获取参数列表
    parameterList() {
      parameterList(this.cateId, this.activeName).then((res) => {
        // console.log(res);
        if (res.meta.status != 200)
          return this.$message.error("获取参数列表失败!");

        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(" ") : [];
          // 控制文本框显示与隐藏
          item.inputVisible = false;
          item.inputValue = "";
        });
        if (this.activeName === "many") {
          this.manyData = res.data;
        } else {
          this.onlyData = res.data;
        }
      });
    },
    // tab点击
    handleClick() {
      // console.log(this.activeName);
      this.parameterList();
    },
    // 退出对话框
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    //添加参数
    addParameter() {
      addParameter(this.cateId, this.addForm.attr_name, this.activeName).then(
        (res) => {
          console.log(res);
          if (res.meta.status != 201)
            return this.$message.error("添加参数失败!");
          this.$message.success("添加参数成功!");
          this.addDialog = false;
          this.parameterList();
        }
      );
    },
    //弹出修改对话框
    showEditDialog(parameterInfo) {
      // console.log(parameterInfo);
      this.editDialog = true;
      this.editForm.attr_name = parameterInfo.attr_name;
      this.editForm.attr_id = parameterInfo.attr_id;
      this.editForm.attr_sel = parameterInfo.attr_sel;
      this.editForm.attr_vals = parameterInfo.attr_vals;
    },
    // 重置
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    //修改参数
    editParameter() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return;
        editParameter(this.cateId, this.editForm).then((res) => {
          // console.log(res);
          if (res.meta.status != 200) return this.$message.error("修改失败!");
          this.$message.success("修改成功");
          this.parameterList();
          this.editDialog = false;
        });
      });
    },
    //删除参数
    removeParams(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          removeParams(this.cateId, id).then((res) => {
            // console.log(res);
            if (res.meta.status != 200) return this.$message.error("删除失败!");
            this.$message.success("删除成功");
            this.parameterList();
          });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    // 文本框失去焦点或者按下Enter触发
    handleInputConfirm() {
      console.log("ok");
    },
    // 点击按钮显示文本框
    showInput(row) {
      row.inputVisible = true;
      // $nextTick 当页面上元素被重新渲染后才会指定回调函数中的代码
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    //文本框失去焦点
    handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = "";
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue.trim());
      row.inputValue = "";
      row.inputVisible = false;
      this.submitEditParameters(row);
    },
    // 删除参数标签
    handleClose(i, row) {
      // console.log(i);
      row.attr_vals.splice(i, 1);
      this.submitEditParameters(row);
    },
    // 提交编辑参数标签
    submitEditParameters(row) {
      submitEditParameters(this.cateId, row).then((res) => {
        console.log(res);
        if (res.meta.status != 200) return this.$message.error("提交失败!");
        this.$message.success(res.meta.msg);
      });
    },
  },
  computed: {
    isBtnDisabled() {
      if (this.selectCateKeys.length !== 3) {
        return true;
      }
      return false;
    },
    cateId() {
      if (this.selectCateKeys.length === 3) {
        return this.selectCateKeys[2];
      }
      return null;
    },
    titleText() {
      if (this.activeName === "many") {
        return "动态参数";
      }
      return "静态属性";
    },
  },
};
</script>

<style lang="less" scoped>
.cat_opt {
  margin: 15px 0;
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 120px;
}
.input-new-tag,
.button-new-tag {
  margin: 10px;
}
</style>